import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import AdminLayout from '../views/admin/AdminLayout.vue'
import EmployeeLayout from '../views/employee/EmployeeLayout.vue'
import Reservation from '../views/admin/Reservation.vue'
import CarStatus from '../views/admin/CarStatus.vue'
import Maintenance from '../views/admin/Maintenance.vue'
import Return from '../views/admin/Return.vue'
import CarManagement from '../views/admin/CarManagement.vue'
import CustomerManagement from '../views/admin/CustomerManagement.vue'
import RentalManagement from '../views/admin/RentalManagement.vue'
import EmployeeManagement from '../views/admin/EmployeeManagement.vue'
import Profile from '../views/admin/Profile.vue'
import ChangePassword from '../views/admin/ChangePassword.vue'
import DataDashboard from '../views/admin/DataDashboard.vue'
import EmployeePage from '../views/employee/EmployeePage.vue'
import EmployeeCreate from '../views/employee/EmployeeCreate.vue'
import EmployeeCustomers from '../views/employee/EmployeeCustomers.vue'
import EmployeeRentals from '../views/employee/EmployeeRentals.vue'
import EmployeeProfile from '../views/employee/EmployeeProfile.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      component: Login,
      meta: { hideNav: true }
    },
    {
      path: '/',
      redirect: () => {
        const userRole = localStorage.getItem('userRole')
        console.log('根路径重定向，用户角色:', userRole)
        if (userRole === 'employee') {
          return '/employee'
        } else {
          return '/data-dashboard'
        }
      }
    },
    // 管理员路由组
    {
      path: '/',
      component: AdminLayout,
      meta: { requiresAuth: true, role: 'admin' },
      children: [
        {
          path: 'data-dashboard',
          component: DataDashboard,
          meta: { requiresAuth: true }
        },
        {
          path: 'reservation',
          component: Reservation,
          meta: { requiresAuth: true }
        },
        {
          path: 'car-status',
          component: CarStatus,
          meta: { requiresAuth: true }
        },
        {
          path: 'maintenance',
          component: Maintenance,
          meta: { requiresAuth: true }
        },
        {
          path: 'return',
          component: Return,
          meta: { requiresAuth: true }
        },
        {
          path: 'car-management',
          component: CarManagement,
          meta: { requiresAuth: true }
        },
        {
          path: 'customer-management',
          component: CustomerManagement,
          meta: { requiresAuth: true }
        },
        {
          path: 'rental-management',
          component: RentalManagement,
          meta: { requiresAuth: true }
        },
        {
          path: 'employee-management',
          component: EmployeeManagement,
          meta: { requiresAuth: true }
        },
        {
          path: 'profile',
          component: Profile,
          meta: { requiresAuth: true }
        },
        {
          path: 'change-password',
          component: ChangePassword,
          meta: { requiresAuth: true }
        }
      ]
    },
    // 员工路由组（使用EmployeeLayout布局）
    {
      path: '/employee',
      component: EmployeeLayout,
      meta: { requiresAuth: true, role: 'employee' },
      children: [
        {
          path: '',
          component: EmployeePage,
          meta: { requiresAuth: true }
        },
        {
          path: 'create',
          component: EmployeeCreate,
          meta: { requiresAuth: true }
        },
        {
          path: 'customers',
          component: EmployeeCustomers,
          meta: { requiresAuth: true }
        },
        {
          path: 'rentals',
          component: EmployeeRentals,
          meta: { requiresAuth: true }
        },
        {
          path: 'profile',
          component: EmployeeProfile,
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  try {
    const token = localStorage.getItem('Token')
    let userRole = localStorage.getItem('userRole')
    
    // 如果没有角色信息，尝试从用户数据中获取
    if (!userRole) {
      const userData = localStorage.getItem('user')
      if (userData) {
        try {
          const user = JSON.parse(userData)
          userRole = user.role || 'admin'
          localStorage.setItem('userRole', userRole)
        } catch (e) {
          userRole = 'admin'
        }
      } else {
        userRole = 'admin'
      }
    }
    
    console.log('路由守卫 - 当前路径:', to.path)
    console.log('Token状态:', token ? '已登录' : '未登录')
    console.log('用户角色:', userRole)
    console.log('目标路由的meta:', to.meta)
    console.log('localStorage中的所有数据:', {
      Token: localStorage.getItem('Token'),
      userRole: localStorage.getItem('userRole'),
      user: localStorage.getItem('user')
    })
    
    if (to.path === '/login') {
      if (token) {
        console.log('已登录用户访问登录页，重定向到对应页面')
        if (userRole === 'employee') {
          console.log('员工用户重定向到 /employee')
          next('/employee')
        } else {
          console.log('管理员用户重定向到 /')
          next('/')
        }
      } else {
        next()
      }
      return
    }
    
    if (to.meta.requiresAuth) {
      if (!token) {
        next('/login')
        return
      }
      
      if (to.meta.role && to.meta.role !== userRole) {
        console.log('角色不匹配！目标路由要求角色:', to.meta.role, '当前用户角色:', userRole)
        if (userRole === 'employee') {
          console.log('重定向员工到 /employee')
          next('/employee')
        } else {
          console.log('重定向管理员到 /')
          next('/')
        }
        return
      }
      
      next()
      return
    }
    
    next()
  } catch (error) {
    console.error('路由导航错误:', error)
    next(false)
  }
})

// 添加全局后置钩子
router.afterEach((to, from) => {
  console.log('导航完成:', { 
    to: to.path, 
    from: from.path,
    requiresAuth: to.meta.requiresAuth,
    token: localStorage.getItem('Token') ? '存在' : '不存在'
  })
})

// 添加全局错误处理
router.onError((error) => {
  console.error('路由错误:', error)
})

export default router
